﻿using FlaUI.Core;
using FlaUI.Core.AutomationElements;
using FlaUI.UIA3;
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using FlaUI.Core.Definitions;
using System.Reflection.Metadata;
using System.Collections.Generic;
using Newtonsoft.Json;
using FlaUI.Core.Conditions;
using FlaUI.Core.WindowsAPI;
using System.Diagnostics;
using FlaUI.Core.Input;
using FlaUI.Core.Identifiers;
using System.IO;
using Service;
using FlaUIAutomation.Model;
using LVYAN.Utils;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace FlaUIAutomation
{

    internal class Program
    {
        static void WriteLog(string Quan, string NickName, string Data)
        {
            try
            {
                //获取当前系统时间
                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                //日志内容
                string write_content = $"\r\n\r\n\r\n  {time}  \r\n\r\n{Quan} {NickName} {Data} ";
                //需要用户自定义日志实现形式
                Console.WriteLine(write_content);
                string fileName = DateTime.Now.ToString("yyyyMMddHH") + ".txt";
                string urlPath = $"Logs/" + DateTime.Now.ToString("yyyyMMdd") + "/" + fileName; // 
                string filePath = AppDomain.CurrentDomain.BaseDirectory + urlPath; // 文件路径
                string directoryName = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write);
                //获得字节数组
                byte[] data = System.Text.Encoding.Default.GetBytes(write_content);
                //开始写入
                fs.Write(data, 0, data.Length);
                //清空缓冲区、关闭流
                fs.Flush();
                fs.Close();
            }
            catch (Exception ex)
            {
                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            }
        }

        static void Main(string[] args)
        {
            {
                //var wx = new WXWork5Automation();
                //var result = wx.Initialize();
                //Console.Write("result" + result);
                //wx.ExploreWXWork5Structure();
                //Console.Write("ExploreWXWork5StructureExploreWXWork5Structure");

            }

            {
                var wx = new WXWork5CoordinateMapper();
                var result = wx.Initialize();
                Console.Write("result1" + result);
                wx.ClickStandardLocations();
                //Console.Write("ExploreWXWork5StructureExploreWXWork5Structure");

            }
            {
                //var wx = new WXWork5PatternDetector();
                //var result = wx.Initialize();
                //Console.Write("result1" + result);
                //wx.DetectWXWork5Patterns();
                //Console.Write("ExploreWXWork5StructureExploreWXWork5Structure");

            }
            {
                //var wx = new WXWork5FunctionalAutomation();
                //var result = wx.Initialize();
                //Console.Write("result1" + result);
                //wx.SearchContact();
                Console.Write("ExploreWXWork5StructureExploreWXWork5Structure");

            }

            Console.ReadLine();
            Console.Read();

            List<string> ListMessage = new List<string>() { };

            Thread.Sleep(5111);
            WriteLog(Quan: "------------------", NickName: "------------------", Data: "------------------");

            //WinProcess winProcess = new WinProcess();
            //winProcess.Kill("WXWork");
            //Process.Start($@"D:\Program Files (x86)\WXWork\WXWork.exe");
            Process[] processes = Process.GetProcessesByName("WXWork");
            foreach (var item in processes)
            {
                WriteLog(Quan: item.Id.ToString(), NickName: item.ProcessName, Data: item.SessionId.ToString());
            }
            if (processes.Length == 0)
            {
                Console.WriteLine("未找到企业微信进程，尝试启动...");
            }

            // 优先选择有主窗口且可见的进程
            foreach (var process in processes)
            {
                try
                {
                    Console.WriteLine($"进程ID: {process.Id}");
                    Console.WriteLine($"进程名: {process.ProcessName}");
                    Console.WriteLine($"启动时间: {process.StartTime}");
                    Console.WriteLine($"内存使用: {process.WorkingSet64 / 1024 / 1024} MB");
                    Console.WriteLine($"主窗口句柄: {process.MainWindowHandle}");
                    Console.WriteLine($"窗口标题: {process.MainWindowTitle}");
                    Console.WriteLine($"是否有界面: {process.MainWindowHandle != IntPtr.Zero}");


                    if (process.MainWindowHandle != IntPtr.Zero && !string.IsNullOrEmpty(process.MainWindowTitle))
                    {
                        Console.WriteLine($"选择主进程: PID={process.Id}, 窗口标题='{process.MainWindowTitle}'");
                        Application.Attach(process);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"检查进程 {process.Id} 失败: {ex.Message}");
                }
            }

            // 如果没有找到有主窗口的进程，选择第一个
            Console.WriteLine($"未找到有主窗口的进程，选择第一个: PID={processes[0].Id}");
            ;


            void PrintChildren(AutomationElement element, int depth)
            {
                var children = element.FindAllChildren();
                foreach (var child in children)
                {
                    Console.WriteLine($"{new string(' ', depth * 2)}Name: {child.Name}, ControlType: {child.ControlType}, AutomationId: {child.AutomationId}");
                    PrintChildren(child, depth + 1);
                }
            }
            try
            {

                //1.附加到微信进程
                using (var app = Application.Attach(processes[0]))
                {
                    using (var automation = new UIA3Automation())
                    {
                        //2.获取主界面
                        var window = app.GetMainWindow(automation);
                        if (window != null)
                        {
                            // 检查窗口的各种属性
                            Console.WriteLine($"  Name: '{window.Name}'");
                            Console.WriteLine($"  ClassName: '{window.ClassName}'");
                            Console.WriteLine($"  ControlType: {window.ControlType}");
                            Console.WriteLine($"  IsEnabled: {window.IsEnabled}");
                            Console.WriteLine($"  BoundingRectangle: {window.BoundingRectangle}");

                            // 如果窗口有名称且可见，很可能是主窗口
                            if (!string.IsNullOrEmpty(window.Name) && window.IsEnabled)
                            {
                                Console.WriteLine($"✅ 选择此进程:窗口名称: '{window.Name}'");
                            }

                            // 2. 通过控件类型查找
                            var allButtons = window.FindAllDescendants(cf => cf.ByControlType(ControlType.Button));
                            var allEditBoxes = window.FindAllDescendants(cf => cf.ByControlType(ControlType.Edit));
                            var panels = window.FindAllDescendants(cf => cf.ByControlType(ControlType.Pane));

                            Console.WriteLine($"找到 {allButtons.Length} 个按钮");
                            Console.WriteLine($"找到 {allEditBoxes.Length} 个编辑框");
                            Console.WriteLine($"找到 {panels.Length} 个面板");
                            for (int i = 0; i < panels.Length; i++)
                            {
                                Console.WriteLine($"\n=== 面板 {i + 1} ===");
                                Console.WriteLine($"名称: '{panels[i].Name}'");
                                Console.WriteLine($"类名: '{panels[i].ClassName}'");
                                Console.WriteLine($"边界: {panels[i].BoundingRectangle}");
                                Console.WriteLine($"是否启用: {panels[i].IsEnabled}");
                                Console.WriteLine($"是否可见: {panels[i].IsAvailable}");

                                // 深入探索面板的子元素
                                ExplorePanelContent(panels[i], 1);
                            }
                            //window.FindFirstDescendant
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"---------------------------------{ex.Message},{ex.InnerException?.Message}");

            }
        }




       

        private static void ExplorePanelContent(AutomationElement panel, int depth)
        {
            var indent = new string(' ', depth * 2);
            var children = panel.FindAllChildren();

            Console.WriteLine($"{indent}包含 {children.Length} 个子元素:");

            foreach (var child in children)
            {
                Console.WriteLine($"{indent}[{child.ControlType}] 名称: '{child.Name}'");

                // 如果是容器类控件，继续深入
                if (IsContainerControl(child.ControlType))
                {
                    ExplorePanelContent(child, depth + 1);
                }

                // 如果是可交互元素，打印详细信息
                if (IsInteractiveControl(child.ControlType))
                {
                    PrintInteractiveElementInfo(child, depth + 1);
                }
            }
        }

        private static bool IsContainerControl(ControlType controlType)
        {
            return controlType == ControlType.Pane ||
                   controlType == ControlType.Group ||
                   controlType == ControlType.Window ||
                   controlType == ControlType.Custom;
        }

        private static bool IsInteractiveControl(ControlType controlType)
        {
            return controlType == ControlType.Button ||
                   controlType == ControlType.Edit ||
                   controlType == ControlType.List ||
                   controlType == ControlType.Tree ||
                   controlType == ControlType.Menu;
        }

        private static void PrintInteractiveElementInfo(AutomationElement element, int depth)
        {
            var indent = new string(' ', depth * 2);
            Console.WriteLine($"{indent}>>> 可交互元素 <<<");
            Console.WriteLine($"{indent}边界: {element.BoundingRectangle}");
            Console.WriteLine($"{indent}可用: {element.IsEnabled}");

            try
            {
                if (!string.IsNullOrEmpty(element.HelpText))
                    Console.WriteLine($"{indent}帮助文本: {element.HelpText}");
            }
            catch { }
        }
    }
}